package templates

import (
	"context"
	"embed"
	"fmt"
	"strconv"
	"strings"
	"unicode"

	"ai-edu/explanation/ai"
	"ai-edu/explanation/models"
	"ai-edu/explanation/prompts"
)

//go:embed *.html
var templateFiles embed.FS

// GetTemplateContent 读取指定模板文件的内容
func GetTemplateContent(templateName string) string {
	fileName := templateName + ".html"
	content, err := templateFiles.ReadFile(fileName)
	if err != nil {
		// 如果读取失败，返回默认模板
		return getDefaultTemplate()
	}
	return string(content)
}

// getDefaultTemplate 返回默认模板
func getDefaultTemplate() string {
	return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数学讲解</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .container { max-width: 800px; margin: 0 auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>数学讲解</h1>
        <div class="content">
            <!-- 内容将在这里动态插入 -->
        </div>
    </div>
</body>
</html>`
}

// -------------------- AI驱动的模板管理器 --------------------

type AITemplateManager struct {
	client *ai.Client
}

func NewAITemplateManager(client *ai.Client) *AITemplateManager {
	return &AITemplateManager{client: client}
}

func (tm *AITemplateManager) Render(ctx context.Context, templateName string, data prompts.TemplatePromptData) (string, error) {
	if tm.client == nil {
		return "", fmt.Errorf("AI客户端未初始化")
	}

	// 读取模板内容
	templateContent := GetTemplateContent(templateName)

	// 使用AI生成HTML内容
	html, err := tm.client.GenerateHTMLTemplate(ctx, templateName, data, templateContent)
	if err != nil {
		return "", fmt.Errorf("AI生成模板失败: %w", err)
	}

	// 清理格式
	return cleanContent(html), nil
}

var globalAITemplateManager *AITemplateManager

func InitGlobalAITemplateManager(client *ai.Client) {
	globalAITemplateManager = NewAITemplateManager(client)
}

func GetGlobalAITemplateManager() *AITemplateManager {
	return globalAITemplateManager
}

// -------------------- 数据结构 --------------------

type TemplateData struct {
	Question        string
	ExplanationText string
	ConceptInfo     string
	Interests       []string
	WrongSubtype    string
	Summary         string
}

// -------------------- 渲染入口（外部调用） --------------------

// RenderTemplate 基于 req 信息和AI生成 HTML
func RenderTemplate(ctx context.Context, client *ai.Client, req models.ExplanationRequest, explanationText, conceptInfo, summary string) (string, error) {
	if client == nil {
		return "", fmt.Errorf("AI客户端未初始化")
	}

	// 构造模板数据（主要基于 req 信息）
	data := prompts.TemplatePromptData{
		Question:        req.Question.Content,
		ExplanationText: explanationText, // AI生成，用于TTS
		ConceptInfo:     conceptInfo,     // 可选的概念信息
		Interests:       req.StudentProfile.Interests,
		WrongSubtype:    req.WrongInfo.Subtype,
		Summary:         summary, // 可选的总结
		WrongInfo:       req.WrongInfo,
		StudentProfile:  req.StudentProfile,
	}

	// 根据错因选择对应模板
	templateName := mapSubtypeToTemplate(req.WrongInfo.Subtype)

	// 读取模板内容
	templateContent := GetTemplateContent(templateName)

	// 使用AI生成HTML内容
	html, err := client.GenerateHTMLTemplate(ctx, templateName, data, templateContent)
	if err != nil {
		return "", fmt.Errorf("AI生成HTML失败: %w", err)
	}

	// 清理格式
	return cleanContent(html), nil
}

// -------------------- 模板选择 --------------------

func mapSubtypeToTemplate(subtype string) string {
	switch subtype {
	// Basic types
	case models.SubtypeUnitMisunderstanding:
		return "basic_unit_misunderstanding"
	case models.SubtypeThreeFactorsConfusion:
		return "basic_three_factors_confusion"
	// Calculation types
	case models.SubtypeFractionAddition:
		return "calculation_fraction_addition"
	case models.SubtypeDecimalCalculation:
		return "calculation_decimal_calculation"
	// Comprehension types
	case models.SubtypeKeywordMismatch:
		return "comprehension_keyword_mismatch"
	case models.SubtypeLogicWrong:
		return "comprehension_logic_wrong"
	default:
		// 根据错因类型判断默认模板
		if strings.HasPrefix(subtype, "basic_") || subtype == "" {
			return "basic_default"
		} else if strings.HasPrefix(subtype, "calculation_") {
			return "calculation_default"
		} else if strings.HasPrefix(subtype, "comprehension_") {
			return "comprehension_default"
		}
		return "basic_default"
	}
}

// -------------------- 清理函数 --------------------

func cleanContent(html string) string {
	html = decodeUnicodeEscapes(html)
	var result strings.Builder
	for _, r := range html {
		if unicode.IsPrint(r) || r == '\n' || r == '\r' || r == '\t' {
			result.WriteRune(r)
		} else if r < 32 {
			result.WriteString(" ")
		}
	}
	return result.String()
}

func decodeUnicodeEscapes(s string) string {
	result := s
	for {
		start := strings.Index(result, "\\u")
		if start == -1 || start+6 > len(result) {
			break
		}
		unicodeStr := result[start : start+6]
		decoded, err := strconv.Unquote(`"` + unicodeStr + `"`)
		if err == nil {
			result = strings.Replace(result, unicodeStr, decoded, 1)
		} else {
			result = result[start+2:]
		}
	}
	result = strings.ReplaceAll(result, "\\n", "\n")
	result = strings.ReplaceAll(result, "\\t", "\t")
	result = strings.ReplaceAll(result, "\\\\", "\\")
	return result
}
